﻿using KC.Domain.Core.EFRepository;
using KC.Domain.Core.Extension;
using KC.Enums.Admin;
using KC.Framework.Base;
using KC.Framework.Extension;
using KC.Framework.SecurityHelper;
using KC.Framework.Tenant;
using KC.Framework.Util;
using KC.Model.Admin;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using Microsoft.Data.SqlClient;
using System.Linq;

namespace KC.DataAccess.Admin
{
    /// <summary>
    /// 数据库初始化操作类
    /// </summary>
    public class ComAdminDatabaseInitializer : MultiTenantSqlServerDatabaseInitializer<ComAdminContext>
    {
        public ComAdminDatabaseInitializer()
            : base()
        { }

        public override ComAdminContext Create(Tenant tenant)
        {
            var dbaTenant = TenantConstant.DbaTenantApiAccessInfo;

            var options = GetCachedDbContextOptions(dbaTenant.TenantName, dbaTenant.ConnectionString, dbaTenant.DatabaseType);
            return new ComAdminContext(options, null, null);
        }

        protected override string GetTargetMigration()
        {
            return KC.DataAccess.Admin.DataInitial.DBSqlInitializer.GetPreMigrationVersion();
        }

        public void SeedData(Tenant tenant)
        {

            using (var context = Create(null))
            {
                var connString = context.Database.GetDbConnection().ConnectionString;
                var builder = new SqlConnectionStringBuilder(connString);
                var server = builder.DataSource;
                var database = builder.InitialCatalog;
                var user = builder.UserID;
                var pwd = builder.Password;
                var hashPwd = EncryptPasswordUtil.EncryptPassword(pwd);

                #region DatabasePool
                var databasePool = new DatabasePool
                {
                    CloudType = CloudType.Azure,
                    DatabaseType = TenantConstant.DefaultDatabaseType,
                    DatabasePoolId = 1,
                    Server = server,
                    Database = database,
                    UserName = user,
                    TenantCount = 2,
                    CanEdit = false,
                    UserPasswordHash = hashPwd,
                    CreatedBy = RoleConstants.AdminUserName
                };
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        //context.DatabasePools.Add(databasePool);

                        //LogUtil.LogDebug(string.Format("---Database----server：{0}; Database: {1}; Password: {2}; PwshHash: {3}", server, database, pwd, hashPwd));
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_DatabasePool] ON ", TenantConstant.DbaTenantName));
                        context.AddOrUpdate(databasePool);
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_DatabasePool] OFF ", TenantConstant.DbaTenantName));
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.LogFatal(string.Format("-------Admin Config insert Database Pool is failed. \r\nMessage: {0}. \r\nStackTrace: {1}", ex.Message, ex.StackTrace));
                    }
                }
                #endregion

                #region StoragePool

                var storagePool = new StoragePool { StoragePoolId = 1 };
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var connecttems = TenantConstant.GetStorageConnectionItems(false);
                        var endpont = connecttems.Item1;
                        var accessName = connecttems.Item2;
                        var accessKey = connecttems.Item3;

                        var storageEncryptKey = EncryptPasswordUtil.EncryptPassword(accessKey);
                        //LogUtil.LogDebug(string.Format("---Storage----Endpoint：{0}; AccountName: {1}; AccountKey: {2}; EncryptKey: {3}", endpont, accessName, accessKey, storageEncryptKey));
                        if (!string.IsNullOrEmpty(endpont))
                        {
                            storagePool = new StoragePool
                            {
                                CloudType = CloudType.Azure,
                                StorageType = TenantConstant.DefaultStorageType,
                                StoragePoolId = 1,
                                Endpoint = endpont,
                                AccessName = accessName,
                                TenantCount = 2,
                                CanEdit = false,
                                AccessKeyPasswordHash = storageEncryptKey,
                                CreatedBy = RoleConstants.AdminUserName
                            };
                        }

                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_StoragePool] ON ", TenantConstant.DbaTenantName));
                        context.AddOrUpdate(storagePool);
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_StoragePool] OFF ", TenantConstant.DbaTenantName));
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.LogFatal(string.Format("-------Admin Config insert Storage Pool is failed. \r\nMessage: {0}. \r\nStackTrace: {1}", ex.Message, ex.StackTrace));
                    }
                }
                #endregion

                #region QueuePool
                var queuePool = new QueuePool { QueuePoolId = 1 };
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var connecttems = TenantConstant.GetQueueConnectionItems(false);
                        var queueEndpont = connecttems.Item1;
                        var queueName = connecttems.Item2;
                        var queueKey = connecttems.Item3;

                        var storageEncryptKey = EncryptPasswordUtil.EncryptPassword(queueKey);
                        //LogUtil.LogDebug(string.Format("---Queue----Endpoint：{0}; AccountName: {1}; AccountKey: {2}; EncryptKey: {3}", queueEndpont, queueName, queueKey, storageEncryptKey));
                        if (!string.IsNullOrEmpty(queueEndpont))
                        {
                            queuePool = new QueuePool
                            {
                                CloudType = CloudType.Azure,
                                QueueType = TenantConstant.DefaultQueueType,
                                QueuePoolId = 1,
                                Endpoint = queueEndpont,
                                AccessName = queueName,
                                TenantCount = 2,
                                CanEdit = false,
                                AccessKeyPasswordHash = storageEncryptKey,
                                CreatedBy = RoleConstants.AdminUserName
                            };
                        }

                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_QueuePool] ON ", TenantConstant.DbaTenantName));
                        context.AddOrUpdate(queuePool);
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_QueuePool] OFF ", TenantConstant.DbaTenantName));
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.LogFatal(string.Format("-------Admin Config insert Queue Pool is failed. \r\nMessage: {0}. \r\nStackTrace: {1}", ex.Message, ex.StackTrace));
                    }
                }
                #endregion

                #region NoSqlPool

                var noSqlPool = new NoSqlPool { NoSqlPoolId = 1 };
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var connecttems = TenantConstant.GetNoSqlConnectionItems(false);
                        var noSqlEndpont = connecttems.Item1;
                        var noSqlName = connecttems.Item2;
                        var noSqlKey = connecttems.Item3;

                        var storageEncryptKey = EncryptPasswordUtil.EncryptPassword(noSqlKey);
                        //LogUtil.LogDebug(string.Format("---NoSql----Endpoint：{0}; AccountName: {1}; AccountKey: {2}; EncryptKey: {3}", noSqlEndpont, noSqlName, noSqlKey, storageEncryptKey));
                        if (!string.IsNullOrEmpty(noSqlEndpont))
                        {
                            noSqlPool = new NoSqlPool
                            {
                                CloudType = CloudType.Azure,
                                NoSqlType = TenantConstant.DefaultNoSqlType,
                                NoSqlPoolId = 1,
                                Endpoint = noSqlEndpont,
                                AccessName = noSqlName,
                                TenantCount = 2,
                                CanEdit = false,
                                AccessKeyPasswordHash = storageEncryptKey,
                                CreatedBy = RoleConstants.AdminUserName
                            };
                        }

                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_NoSqlPool] ON ", TenantConstant.DbaTenantName));
                        context.AddOrUpdate(noSqlPool);
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_NoSqlPool] OFF ", TenantConstant.DbaTenantName));
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.LogFatal(string.Format("-------Admin Config insert NoSql Pool is failed. \r\nMessage: {0}. \r\nStackTrace: {1}", ex.Message, ex.StackTrace));
                    }
                }
                #endregion

                #region ServiceBusPool

                var serviceBusPool = new ServiceBusPool { ServiceBusPoolId = 1 };
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var connecttems = TenantConstant.GetServiceBusConnectionItems(false);
                        var serviceBusEndpont = connecttems.Item1;
                        var serviceBusName = connecttems.Item2;
                        var serviceBusKey = connecttems.Item3;

                        var storageEncryptKey = EncryptPasswordUtil.EncryptPassword(serviceBusKey);
                        //LogUtil.LogDebug(string.Format("---ServiceBus----Endpoint：{0}; AccountName: {1}; AccountKey: {2}; EncryptKey: {3}", serviceBusEndpont, serviceBusName, serviceBusKey, storageEncryptKey));
                        if (!string.IsNullOrEmpty(serviceBusEndpont))
                        {
                            serviceBusPool = new ServiceBusPool
                            {
                                CloudType = CloudType.Azure,
                                DistributedMessageType = TenantConstant.DefaultServiceBusType,
                                ServiceBusPoolId = 1,
                                Endpoint = serviceBusEndpont,
                                AccessName = serviceBusName,
                                TenantCount = 2,
                                CanEdit = false,
                                AccessKeyPasswordHash = storageEncryptKey,
                                CreatedBy = RoleConstants.AdminUserName
                            };
                        }

                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_ServiceBusPool] ON ", TenantConstant.DbaTenantName));
                        context.AddOrUpdate(serviceBusPool);
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_ServiceBusPool] OFF ", TenantConstant.DbaTenantName));
                        transaction.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        LogUtil.LogFatal(string.Format("-------Admin Config insert ServiceBus Pool is failed. \r\nMessage: {0}. \r\nStackTrace: {1}", ex.Message, ex.StackTrace));
                    }
                }
                #endregion

                //#region Tenant's Application
                //var ssodomain = GlobalConfig.AccWebDomain.TrimEnd('/').Replace("http://", "").Replace("https://", "");
                //var crmdomain = GlobalConfig.CrmWebDomain.TrimEnd('/').Replace("http://", "").Replace("https://", "");
                //var portaldomain = GlobalConfig.PortalWebDomain.TrimEnd('/').Replace("http://", "").Replace("https://", "");
                //var marketdomain = GlobalConfig.JRWebDomain.TrimEnd('/').Replace("http://", "").Replace("https://", "");
                //var trndomain = GlobalConfig.TrainWebDomain.TrimEnd('/').Replace("http://", "").Replace("https://", "");
                //var flowdomain = GlobalConfig.FlowWebDomain.TrimEnd('/').Replace("http://", "").Replace("https://", "");
                //var apidomain = GlobalConfig.ApiWebDomain.Replace("http://", "").Replace("https://", "") + "api";

                //#region cDba Tenant's Application

                //var ssoApp = new TenantUserApplication()
                //{
                //    Id = 1,
                //    TenantId = TenantConstant.DbaTenantId,
                //    ApplicationId = ApplicationConstant.SsoAppId,
                //    ApplicationName = ApplicationConstant.SsoAppName,
                //    DomainName = ssodomain.Replace(TenantConstant.SubDomain, TenantConstant.DbaTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "sso",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 1,
                //            ApplicationId = 1,
                //            ModuleId = ApplicationConstant.SsoAccountModuleId,
                //            ModuleName = "系统管理",
                //            Description = "系统管理：KC.DataAccess.Account",
                //            AssemblyName = "KC.DataAccess.Account",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 2,
                //            ApplicationId = 1,
                //            ModuleId = ApplicationConstant.SsoAdminModuleId,
                //            ModuleName = "租户管理",
                //            Description = "租户管理：KC.DataAccess.Admin",
                //            AssemblyName = "KC.DataAccess.Admin",
                //        }
                //    }
                //};

                //#endregion

                //#region cTest Tenant's Application
                //var ssoApp1 = new TenantUserApplication()
                //{
                //    Id = 4,
                //    TenantId = TenantConstant.TestTenantId,
                //    ApplicationId = ApplicationConstant.SsoAppId,
                //    ApplicationName = ApplicationConstant.SsoAppName,
                //    DomainName = ssodomain.Replace(TenantConstant.SubDomain, TenantConstant.TestTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "sso",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 5,
                //            ApplicationId = 4,
                //            ModuleId = ApplicationConstant.SsoAccountModuleId,
                //            ModuleName = "系统管理",
                //            Description = "系统管理：KC.DataAccess.Account",
                //            AssemblyName = "KC.DataAccess.Account",
                //        }
                //    }
                //};

                //var crmApp1 = new TenantUserApplication()
                //{
                //    Id = 5,
                //    TenantId = TenantConstant.TestTenantId,
                //    ApplicationId = ApplicationConstant.CrmAppId,
                //    ApplicationName = ApplicationConstant.CrmAppName,
                //    DomainName = crmdomain.Replace(TenantConstant.SubDomain, TenantConstant.TestTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.Shop_IN_0_crm",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 6,
                //            ApplicationId = 5,
                //            ModuleId = ApplicationConstant.CrmBasicModuleId,
                //            ModuleName = "客户管理",
                //            Description = "客户管理：KC.DataAccess.Customer",
                //            AssemblyName = "KC.DataAccess.Customer",
                //        },
                //    }
                //};

                //var portalApp1 = new TenantUserApplication()
                //{
                //    Id = 6,
                //    TenantId = TenantConstant.TestTenantId,
                //    ApplicationId = ApplicationConstant.PortalAppId,
                //    ApplicationName = "电商系统",
                //    DomainName = portaldomain.Replace(TenantConstant.SubDomain, TenantConstant.TestTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.Shop_IN_0_portal",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 7,
                //            ApplicationId = 6,
                //            ModuleId = ApplicationConstant.ShopBasicModuleId,
                //            ModuleName = "商铺模块",
                //            Description = "商铺模块：KC.DataAccess.Shop",
                //            AssemblyName = "KC.DataAccess.Shop",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 8,
                //            ApplicationId = 6,
                //            ModuleId = ApplicationConstant.ShopOfferingModuleId,
                //            ModuleName = "产品模块",
                //            Description = "产品模块：KC.DataAccess.Offering",
                //            AssemblyName = "KC.DataAccess.Offering",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 9,
                //            ApplicationId = 6,
                //            ModuleId = ApplicationConstant.ShopOrderModuleId,
                //            ModuleName = "订单模块",
                //            Description = "订单模块：KC.DataAccess.Order",
                //            AssemblyName = "KC.DataAccess.Order",
                //        },
                //    }
                //};
                //var marketApp1 = new TenantUserApplication()
                //{
                //    Id = 7,
                //    TenantId = TenantConstant.TestTenantId,
                //    ApplicationId = ApplicationConstant.MarketAppId,
                //    ApplicationName = ApplicationConstant.MarketAppName,
                //    DomainName = marketdomain.Replace(TenantConstant.SubDomain, TenantConstant.TestTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.Shop_IN_0_market",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 10,
                //            ApplicationId = 7,
                //            ModuleId = ApplicationConstant.MarketBasicModuleId,
                //            ModuleName = "商铺模块",
                //            Description = "商铺模块：KC.DataAccess.Shop",
                //            AssemblyName = "KC.DataAccess.Shop",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 11,
                //            ApplicationId = 7,
                //            ModuleId = ApplicationConstant.MarketOfferingModuleId,
                //            ModuleName = "融资产品模块",
                //            Description = "融资产品模块：KC.DataAccess.FinancingOffering",
                //            AssemblyName = "KC.DataAccess.FinancingOffering",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 12,
                //            ApplicationId = 7,
                //            ModuleId = ApplicationConstant.MarketOrderModuleId,
                //            ModuleName = "融资订单模块",
                //            Description = "融资订单模块：KC.DataAccess.FinancingOrder",
                //            AssemblyName = "KC.DataAccess.FinancingOrder",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 13,
                //            ApplicationId = 7,
                //            ModuleId = ApplicationConstant.MarketCreditLevelModuleId,
                //            ModuleName = "信用评级模块",
                //            Description = "信用评级模块：KC.DataAccess.CreditLevel",
                //            AssemblyName = "KC.DataAccess.CreditLevel",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 14,
                //            ApplicationId = 7,
                //            ModuleId = ApplicationConstant.MarketFinancingCreditModuleId,
                //            ModuleName = "额度管理模块",
                //            Description = "额度管理模块：KC.DataAccess.FinancingCredit",
                //            AssemblyName = "KC.DataAccess.FinancingCredit",
                //        },
                //    }
                //};
                //var apiApp1 = new TenantUserApplication()
                //{
                //    Id = 8,
                //    TenantId = TenantConstant.TestTenantId,
                //    ApplicationId = ApplicationConstant.WebapiAppId,
                //    ApplicationName = ApplicationConstant.WebapiAppName,
                //    DomainName = apidomain.Replace(TenantConstant.SubDomain, TenantConstant.TestTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.SSO_IN_0_api",
                //};
                //var erpApp1 = new TenantUserApplication()
                //{
                //    Id = 9,
                //    TenantId = TenantConstant.TestTenantId,
                //    ApplicationId = ApplicationConstant.TrainAppId,
                //    ApplicationName = ApplicationConstant.TrainAppName,
                //    DomainName = trndomain.Replace(TenantConstant.SubDomain, TenantConstant.TestTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.SSO_IN_0_erp",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 15,
                //            ApplicationId = 9,
                //            ModuleId = ApplicationConstant.ErpBasicModuleId,
                //            ModuleName = "ERP基础模块",
                //            Description = "ERP基础模块：KC.DataAccess.Erp",
                //            AssemblyName = "KC.DataAccess.Erp",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 16,
                //            ApplicationId = 9,
                //            ModuleId = ApplicationConstant.ErpScmModuleId,
                //            ModuleName = "供应链管理",
                //            Description = "供应链管理：KC.DataAccess.Scm",
                //            AssemblyName = "KC.DataAccess.Scm",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 17,
                //            ApplicationId = 9,
                //            ModuleId = ApplicationConstant.ErpFinanceModuleId,
                //            ModuleName = "财务模块",
                //            Description = "财务模块：KC.DataAccess.Finance",
                //            AssemblyName = "KC.DataAccess.Finance",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 19,
                //            ApplicationId = 9,
                //            ModuleId = ApplicationConstant.ErpArapModuleId,
                //            ModuleName = "应收应付模块",
                //            Description = "应收应付模块：KC.DataAccess.Arap",
                //            AssemblyName = "KC.DataAccess.Arap",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 20,
                //            ApplicationId = 9,
                //            ModuleId = ApplicationConstant.ErpCashierModuleId,
                //            ModuleName = "现金账模块",
                //            Description = "现金账模块：KC.DataAccess.Cashier",
                //            AssemblyName = "KC.DataAccess.Cashier",
                //        },
                //    }
                //};
                //var flowApp1 = new TenantUserApplication()
                //{
                //    Id = 10,
                //    TenantId = TenantConstant.TestTenantId,
                //    ApplicationId = ApplicationConstant.FlowAppId,
                //    ApplicationName = ApplicationConstant.FlowAppName,
                //    DomainName = flowdomain.Replace(TenantConstant.SubDomain, TenantConstant.TestTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.SSO_IN_0_flow",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 18,
                //            ApplicationId = 10,
                //            ModuleId = ApplicationConstant.WorkflowBasicModuleId,
                //            ModuleName = "Workflow基础模块",
                //            Description = "Workflow基础模块：KC.DataAccess.WorkFlow",
                //            AssemblyName = "KC.DataAccess.WorkFlow",
                //        },
                //    }
                //};

                //#endregion

                //#region cBuy Tenant's Application
                //var ssoApp2 = new TenantUserApplication()
                //{
                //    Id = 14,
                //    TenantId = TenantConstant.BuyTenantId,
                //    ApplicationId = ApplicationConstant.SsoAppId,
                //    ApplicationName = ApplicationConstant.SsoAppName,
                //    DomainName = ssodomain.Replace(TenantConstant.SubDomain, TenantConstant.BuyTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.SSO_IN_0_Web",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 15,
                //            ApplicationId = 14,
                //            ModuleId = ApplicationConstant.SsoAccountModuleId,
                //            ModuleName = "系统管理",
                //            Description = "系统管理：KC.DataAccess.Account",
                //            AssemblyName = "KC.DataAccess.Account",
                //        }
                //    }
                //};

                //var crmApp2 = new TenantUserApplication()
                //{
                //    Id = 15,
                //    TenantId = TenantConstant.BuyTenantId,
                //    ApplicationId = ApplicationConstant.CrmAppId,
                //    ApplicationName = ApplicationConstant.CrmAppName,
                //    DomainName = crmdomain.Replace(TenantConstant.SubDomain, TenantConstant.BuyTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.Shop_IN_0_crm",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 16,
                //            ApplicationId = 15,
                //            ModuleId = ApplicationConstant.CrmBasicModuleId,
                //            ModuleName = "客户管理",
                //            Description = "客户管理：KC.DataAccess.Customer",
                //            AssemblyName = "KC.DataAccess.Customer",
                //        },
                //    }
                //};

                //var portalApp2 = new TenantUserApplication()
                //{
                //    Id = 16,
                //    TenantId = TenantConstant.BuyTenantId,
                //    ApplicationId = ApplicationConstant.PortalAppId,
                //    ApplicationName = "电商系统",
                //    DomainName = portaldomain.Replace(TenantConstant.SubDomain, TenantConstant.BuyTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.Shop_IN_0_portal",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 17,
                //            ApplicationId = 16,
                //            ModuleId = ApplicationConstant.ShopBasicModuleId,
                //            ModuleName = "商铺模块",
                //            Description = "商铺模块：KC.DataAccess.Shop",
                //            AssemblyName = "KC.DataAccess.Shop",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 18,
                //            ApplicationId = 16,
                //            ModuleId = ApplicationConstant.ShopOfferingModuleId,
                //            ModuleName = "产品模块",
                //            Description = "产品模块：KC.DataAccess.Offering",
                //            AssemblyName = "KC.DataAccess.Offering",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 19,
                //            ApplicationId = 16,
                //            ModuleId = ApplicationConstant.ShopOrderModuleId,
                //            ModuleName = "订单模块",
                //            Description = "订单模块：KC.DataAccess.Order",
                //            AssemblyName = "KC.DataAccess.Order",
                //        },
                //    }
                //};
                //var marketApp2 = new TenantUserApplication()
                //{
                //    Id = 17,
                //    TenantId = TenantConstant.BuyTenantId,
                //    ApplicationId = ApplicationConstant.MarketAppId,
                //    ApplicationName = ApplicationConstant.MarketAppName,
                //    DomainName = marketdomain.Replace(TenantConstant.SubDomain, TenantConstant.BuyTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.Shop_IN_0_market",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 20,
                //            ApplicationId = 17,
                //            ModuleId = ApplicationConstant.MarketBasicModuleId,
                //            ModuleName = "商铺模块",
                //            Description = "商铺模块：KC.DataAccess.Shop",
                //            AssemblyName = "KC.DataAccess.Shop",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 21,
                //            ApplicationId = 17,
                //            ModuleId = ApplicationConstant.MarketOfferingModuleId,
                //            ModuleName = "融资产品模块",
                //            Description = "融资产品模块：KC.DataAccess.FinancingOffering",
                //            AssemblyName = "KC.DataAccess.FinancingOffering",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 22,
                //            ApplicationId = 17,
                //            ModuleId = ApplicationConstant.MarketOrderModuleId,
                //            ModuleName = "融资订单模块",
                //            Description = "融资订单模块：KC.DataAccess.FinancingOrder",
                //            AssemblyName = "KC.DataAccess.FinancingOrder",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 23,
                //            ApplicationId = 17,
                //            ModuleId = ApplicationConstant.MarketCreditLevelModuleId,
                //            ModuleName = "信用评级模块",
                //            Description = "信用评级模块：KC.DataAccess.CreditLevel",
                //            AssemblyName = "KC.DataAccess.CreditLevel",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 24,
                //            ApplicationId = 17,
                //            ModuleId = ApplicationConstant.MarketFinancingCreditModuleId,
                //            ModuleName = "额度管理模块",
                //            Description = "额度管理模块：KC.DataAccess.FinancingCredit",
                //            AssemblyName = "KC.DataAccess.FinancingCredit",
                //        },
                //    }
                //};
                //var apiApp2 = new TenantUserApplication()
                //{
                //    Id = 18,
                //    TenantId = TenantConstant.BuyTenantId,
                //    ApplicationId = ApplicationConstant.WebapiAppId,
                //    ApplicationName = ApplicationConstant.WebapiAppName,
                //    DomainName = apidomain.Replace(TenantConstant.SubDomain, TenantConstant.BuyTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.SSO_IN_0_api",
                //};
                //var erpApp2 = new TenantUserApplication()
                //{
                //    Id = 19,
                //    TenantId = TenantConstant.BuyTenantId,
                //    ApplicationId = ApplicationConstant.TrainAppId,
                //    ApplicationName = ApplicationConstant.TrainAppName,
                //    DomainName = trndomain.Replace(TenantConstant.SubDomain, TenantConstant.BuyTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.SSO_IN_0_erp",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 25,
                //            ApplicationId = 19,
                //            ModuleId = ApplicationConstant.ErpBasicModuleId,
                //            ModuleName = "ERP基础模块",
                //            Description = "ERP基础模块：KC.DataAccess.Erp",
                //            AssemblyName = "KC.DataAccess.Erp",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 26,
                //            ApplicationId = 19,
                //            ModuleId = ApplicationConstant.ErpScmModuleId,
                //            ModuleName = "供应链管理",
                //            Description = "供应链管理：KC.DataAccess.Scm",
                //            AssemblyName = "KC.DataAccess.Scm",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 27,
                //            ApplicationId = 19,
                //            ModuleId = ApplicationConstant.ErpFinanceModuleId,
                //            ModuleName = "财务模块",
                //            Description = "财务模块：KC.DataAccess.Finance",
                //            AssemblyName = "KC.DataAccess.Finance",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 29,
                //            ApplicationId = 19,
                //            ModuleId = ApplicationConstant.ErpArapModuleId,
                //            ModuleName = "应收应付模块",
                //            Description = "应收应付模块：KC.DataAccess.Arap",
                //            AssemblyName = "KC.DataAccess.Arap",
                //        },
                //        new TenantUserAppModule()
                //        {
                //            Id = 30,
                //            ApplicationId = 19,
                //            ModuleId = ApplicationConstant.ErpCashierModuleId,
                //            ModuleName = "现金账模块",
                //            Description = "现金账模块：KC.DataAccess.Cashier",
                //            AssemblyName = "KC.DataAccess.Cashier",
                //        },
                //    }
                //};
                //var flowApp2 = new TenantUserApplication()
                //{
                //    Id = 20,
                //    TenantId = TenantConstant.BuyTenantId,
                //    ApplicationId = ApplicationConstant.FlowAppId,
                //    ApplicationName = ApplicationConstant.FlowAppName,
                //    DomainName = flowdomain.Replace(TenantConstant.SubDomain, TenantConstant.BuyTenantName),
                //    AppStatus = ApplicationStatus.OpenSuccess,
                //    WebSiteName = "KC.Portal.SSO_IN_0_flow",
                //    ApplicationModules = new List<TenantUserAppModule>()
                //    {
                //        new TenantUserAppModule()
                //        {
                //            Id = 28,
                //            ApplicationId = 20,
                //            ModuleId = ApplicationConstant.WorkflowBasicModuleId,
                //            ModuleName = "Workflow基础模块",
                //            Description = "Workflow基础模块：KC.DataAccess.WorkFlow",
                //            AssemblyName = "KC.DataAccess.WorkFlow",
                //        },
                //    }
                //};

                //#endregion

                //var apps = new List<TenantUserApplication>()
                //{
                //    ssoApp, ssoApp1, crmApp1, portalApp1, marketApp1, apiApp1, erpApp1, flowApp1,
                //    ssoApp2, crmApp2, portalApp2, marketApp2, apiApp2, erpApp2, flowApp2
                //};

                //var appModules = apps.SelectMany(m => m.ApplicationModules).ToList();

                //#endregion

                #region Tenant's Setting
                #region cDba Tenant's Setting
                var cdbaTenantSetting = new List<TenantUserSetting>()
                {
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 1,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_EmailSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_EmailLimit,
                        CanEdit = true,
                        Index = 1
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 2,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_SmsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_SmsLimit,
                        CanEdit = true,
                        Index = 2
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 3,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_PaymentSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_PaymentLimit,
                        CanEdit = true,
                        Index = 3
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 4,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_IDSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_IDLimit,
                        CanEdit = true,
                        Index = 4
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 5,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_CallSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_CallLimit,
                        CanEdit = true,
                        Index = 5
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 6,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_LogisticsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_LogisticsLimit,
                        CanEdit = true,
                        Index = 6
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 7,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_WeixinSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 7
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 8,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_ContractSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_ContractLimit,
                        CanEdit = true,
                        Index = 8
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.DbaTenantId,
                        PropertyAttributeId = 9,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_OwnDomainSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 9
                    }
                };
                #endregion

                #region cTest Tenant's Setting
                var ctestTenantSetting = new List<TenantUserSetting>()
                {
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 11,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_EmailSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_EmailLimit,
                        CanEdit = true,
                        Index = 1
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 12,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_SmsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_SmsLimit,
                        CanEdit = true,
                        Index = 2
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 13,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_PaymentSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_PaymentLimit,
                        CanEdit = true,
                        Index = 3
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 14,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_IDSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_IDLimit,
                        CanEdit = true,
                        Index = 4
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 15,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_CallSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_CallLimit,
                        CanEdit = true,
                        Index = 5
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 16,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_LogisticsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_LogisticsLimit,
                        CanEdit = true,
                        Index = 6
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 17,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_WeixinSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 7
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 18,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_ContractSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_ContractLimit,
                        CanEdit = true,
                        Index = 8
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.TestTenantId,
                        PropertyAttributeId = 19,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_OwnDomainSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 9
                    }

                };
                #endregion

                #region cBuy Tenant's Setting
                var cbuyTenantSetting = new List<TenantUserSetting>()
                {
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 21,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_EmailSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_EmailLimit,
                        CanEdit = true,
                        Index = 1
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 22,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_SmsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_SmsLimit,
                        CanEdit = true,
                        Index = 2
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 23,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_PaymentSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_PaymentLimit,
                        CanEdit = true,
                        Index = 3
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 24,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_IDSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_IDLimit,
                        CanEdit = true,
                        Index = 4
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 25,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_CallSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_CallLimit,
                        CanEdit = true,
                        Index = 5
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 26,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_LogisticsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_LogisticsLimit,
                        CanEdit = true,
                        Index = 6
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 27,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_WeixinSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 7
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 28,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_ContractSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_ContractLimit,
                        CanEdit = true,
                        Index = 8
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.BuyTenantId,
                        PropertyAttributeId = 29,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_OwnDomainSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 9
                    }

                };
                #endregion

                #region cSale Tenant's Setting
                var csaleTenantSetting = new List<TenantUserSetting>()
                {
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 31,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_EmailSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_EmailLimit,
                        CanEdit = true,
                        Index = 1
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 32,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_SmsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_SmsLimit,
                        CanEdit = true,
                        Index = 2
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 33,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_PaymentSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_PaymentLimit,
                        CanEdit = true,
                        Index = 3
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 34,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_IDSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_IDLimit,
                        CanEdit = true,
                        Index = 4
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 35,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_CallSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_CallLimit,
                        CanEdit = true,
                        Index = 5
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 36,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_LogisticsSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_LogisticsLimit,
                        CanEdit = true,
                        Index = 6
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 37,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_WeixinSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 7
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 38,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_ContractSetting,
                        Value = "true",
                        Value1 = TenantConstant.Default_ContractLimit,
                        CanEdit = true,
                        Index = 8
                    },
                    new TenantUserSetting()
                    {
                        TenantId = TenantConstant.SaleTenantId,
                        PropertyAttributeId = 39,
                        DataType = AttributeDataType.Bool,
                        Name = TenantConstant.PropertyName_OwnDomainSetting,
                        Value = "true",
                        CanEdit = true,
                        Index = 9
                    }
                };
                #endregion

                var settins = new List<TenantUserSetting>();
                settins.AddRange(cdbaTenantSetting);
                settins.AddRange(ctestTenantSetting);
                settins.AddRange(cbuyTenantSetting);
                settins.AddRange(csaleTenantSetting);
                #endregion

                #region Tenant
                using (var transaction = context.Database.BeginTransaction())
                {
                    var tDba = TenantConstant.DbaTenantApiAccessInfo;
                    var tenantDba = new TenantUser
                    {
                        CloudType = tDba.CloudType,
                        TenantType = tDba.TenantType,
                        Version = tDba.Version,
                        TenantId = tDba.TenantId,
                        TenantName = tDba.TenantName,
                        TenantDisplayName = tDba.TenantDisplayName,
                        TenantSignature = tDba.TenantSignature,
                        PrivateEncryptKey = tDba.PrivateEncryptKey,
                        Server = tDba.Server,
                        Database = tDba.Database,
                        DatabasePasswordHash = tDba.DatabasePasswordHash,
                        StorageEndpoint = tDba.StorageEndpoint,
                        StorageAccessName = tDba.StorageAccessName,
                        StorageAccessKeyPasswordHash = tDba.StorageAccessKeyPasswordHash,
                        QueueEndpoint = tDba.QueueEndpoint,
                        QueueAccessName = tDba.QueueAccessName,
                        QueueAccessKeyPasswordHash = tDba.QueueAccessKeyPasswordHash,
                        NoSqlEndpoint = tDba.NoSqlEndpoint,
                        NoSqlAccessName = tDba.NoSqlAccessName,
                        NoSqlAccessKeyPasswordHash = tDba.NoSqlAccessKeyPasswordHash,
                        ServiceBusEndpoint = tDba.ServiceBusEndpoint,
                        ServiceBusAccessName = tDba.ServiceBusAccessName,
                        ServiceBusAccessKeyPasswordHash = tDba.ServiceBusAccessKeyPasswordHash,
                        ContactName = tDba.ContactName,
                        ContactEmail = tDba.ContactEmail,
                        ContactPhone = tDba.ContactPhone,
                        DatabasePoolId = databasePool.DatabasePoolId,
                        StoragePoolId = storagePool.StoragePoolId,
                        QueuePoolId = queuePool.QueuePoolId,
                        NoSqlPoolId = noSqlPool.NoSqlPoolId,
                        ServiceBusPoolId = serviceBusPool.ServiceBusPoolId,
                        CanEdit = false,
                        CreatedBy = RoleConstants.AdminUserName,
                        TenantSettings = cdbaTenantSetting,
                        //Applications = new List<TenantUserApplication>() { ssoApp }
                    };

                    var tTest = TenantConstant.TestTenantApiAccessInfo;
                    var tenantDev = new TenantUser
                    {
                        CloudType = tTest.CloudType,
                        TenantType = tTest.TenantType,
                        Version = tTest.Version,
                        TenantId = tTest.TenantId,
                        TenantName = tTest.TenantName,
                        TenantDisplayName = tTest.TenantDisplayName,
                        TenantSignature = tTest.TenantSignature,
                        PrivateEncryptKey = tTest.PrivateEncryptKey,
                        Server = tTest.Server,
                        Database = tTest.Database,
                        DatabasePasswordHash = tTest.DatabasePasswordHash,
                        StorageEndpoint = tTest.StorageEndpoint,
                        StorageAccessName = tTest.StorageAccessName,
                        StorageAccessKeyPasswordHash = tTest.StorageAccessKeyPasswordHash,
                        QueueEndpoint = tTest.QueueEndpoint,
                        QueueAccessName = tTest.QueueAccessName,
                        QueueAccessKeyPasswordHash = tTest.QueueAccessKeyPasswordHash,
                        NoSqlEndpoint = tTest.NoSqlEndpoint,
                        NoSqlAccessName = tTest.NoSqlAccessName,
                        NoSqlAccessKeyPasswordHash = tTest.NoSqlAccessKeyPasswordHash,
                        ServiceBusEndpoint = tTest.ServiceBusEndpoint,
                        ServiceBusAccessName = tTest.ServiceBusAccessName,
                        ServiceBusAccessKeyPasswordHash = tTest.ServiceBusAccessKeyPasswordHash,
                        ContactName = tTest.ContactName,
                        ContactEmail = tTest.ContactEmail,
                        ContactPhone = tTest.ContactPhone,
                        DatabasePoolId = databasePool.DatabasePoolId,
                        StoragePoolId = storagePool.StoragePoolId,
                        QueuePoolId = queuePool.QueuePoolId,
                        NoSqlPoolId = noSqlPool.NoSqlPoolId,
                        ServiceBusPoolId = serviceBusPool.ServiceBusPoolId,
                        CanEdit = false,
                        CreatedBy = RoleConstants.AdminUserName,
                        TenantSettings = ctestTenantSetting,
                        //Applications = new List<TenantUserApplication>() { ssoApp }
                    };

                    var tBuy = TenantConstant.BuyTenantApiAccessInfo;
                    var tenantBuy = new TenantUser
                    {
                        CloudType = tBuy.CloudType,
                        TenantType = tBuy.TenantType,
                        Version = tBuy.Version,
                        TenantId = tBuy.TenantId,
                        TenantName = tBuy.TenantName,
                        TenantDisplayName = tBuy.TenantDisplayName,
                        TenantSignature = tBuy.TenantSignature,
                        PrivateEncryptKey = tBuy.PrivateEncryptKey,
                        Server = tBuy.Server,
                        Database = tBuy.Database,
                        DatabasePasswordHash = tBuy.DatabasePasswordHash,
                        StorageEndpoint = tBuy.StorageEndpoint,
                        StorageAccessName = tBuy.StorageAccessName,
                        StorageAccessKeyPasswordHash = tBuy.StorageAccessKeyPasswordHash,
                        QueueEndpoint = tBuy.QueueEndpoint,
                        QueueAccessName = tBuy.QueueAccessName,
                        QueueAccessKeyPasswordHash = tBuy.QueueAccessKeyPasswordHash,
                        NoSqlEndpoint = tBuy.NoSqlEndpoint,
                        NoSqlAccessName = tBuy.NoSqlAccessName,
                        NoSqlAccessKeyPasswordHash = tBuy.NoSqlAccessKeyPasswordHash,
                        ServiceBusEndpoint = tBuy.ServiceBusEndpoint,
                        ServiceBusAccessName = tBuy.ServiceBusAccessName,
                        ServiceBusAccessKeyPasswordHash = tBuy.ServiceBusAccessKeyPasswordHash,
                        ContactName = tBuy.ContactName,
                        ContactEmail = tBuy.ContactEmail,
                        ContactPhone = tBuy.ContactPhone,
                        DatabasePoolId = databasePool.DatabasePoolId,
                        StoragePoolId = storagePool.StoragePoolId,
                        QueuePoolId = queuePool.QueuePoolId,
                        NoSqlPoolId = noSqlPool.NoSqlPoolId,
                        ServiceBusPoolId = serviceBusPool.ServiceBusPoolId,
                        CanEdit = false,
                        CreatedBy = RoleConstants.AdminUserName,
                        TenantSettings = cbuyTenantSetting,
                        //Applications = new List<TenantUserApplication>() { ssoApp }
                    };

                    var tSale = TenantConstant.SaleTenantApiAccessInfo;
                    var tenantSale = new TenantUser
                    {
                        CloudType = tSale.CloudType,
                        TenantType = tSale.TenantType,
                        Version = tSale.Version,
                        TenantId = tSale.TenantId,
                        TenantName = tSale.TenantName,
                        TenantDisplayName = tSale.TenantDisplayName,
                        TenantSignature = tSale.TenantSignature,
                        PrivateEncryptKey = tSale.PrivateEncryptKey,
                        Server = tSale.Server,
                        Database = tSale.Database,
                        DatabasePasswordHash = tSale.DatabasePasswordHash,
                        StorageEndpoint = tSale.StorageEndpoint,
                        StorageAccessName = tSale.StorageAccessName,
                        StorageAccessKeyPasswordHash = tSale.StorageAccessKeyPasswordHash,
                        QueueEndpoint = tSale.QueueEndpoint,
                        QueueAccessName = tSale.QueueAccessName,
                        QueueAccessKeyPasswordHash = tSale.QueueAccessKeyPasswordHash,
                        NoSqlEndpoint = tSale.NoSqlEndpoint,
                        NoSqlAccessName = tSale.NoSqlAccessName,
                        NoSqlAccessKeyPasswordHash = tSale.NoSqlAccessKeyPasswordHash,
                        ServiceBusEndpoint = tSale.ServiceBusEndpoint,
                        ServiceBusAccessName = tSale.ServiceBusAccessName,
                        ServiceBusAccessKeyPasswordHash = tSale.ServiceBusAccessKeyPasswordHash,
                        ContactName = tSale.ContactName,
                        ContactEmail = tSale.ContactEmail,
                        ContactPhone = tSale.ContactPhone,
                        DatabasePoolId = databasePool.DatabasePoolId,
                        StoragePoolId = storagePool.StoragePoolId,
                        QueuePoolId = queuePool.QueuePoolId,
                        NoSqlPoolId = noSqlPool.NoSqlPoolId,
                        ServiceBusPoolId = serviceBusPool.ServiceBusPoolId,
                        CanEdit = false,
                        CreatedBy = RoleConstants.AdminUserName,
                        TenantSettings = csaleTenantSetting,
                        //Applications = new List<TenantUserApplication>() { ssoApp }
                    };

                    try
                    {
                        //context.TenantUsers.Add(tenantDba);
                        //context.TenantUsers.Add(tenantDev);
                        //context.TenantUsers.Add(tenantBuy);
                        //context.TenantUsers.Add(tenantSale);

                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUser] ON ", TenantConstant.DbaTenantName));
                        context.AddOrUpdate(tenantDba);
                        context.AddOrUpdate(tenantDev);
                        context.AddOrUpdate(tenantBuy);
                        context.AddOrUpdate(tenantSale);
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUser] OFF ", TenantConstant.DbaTenantName));

                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUserSetting] ON ", TenantConstant.DbaTenantName));
                        context.AddOrUpdates(settins);
                        context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUserSetting] OFF ", TenantConstant.DbaTenantName));

                        //context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUserApplication] ON ", TenantConstant.DbaTenantName));
                        //context.AddOrUpdates(apps);
                        //context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUserApplication] OFF ", TenantConstant.DbaTenantName));

                        //context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUserAppModule] ON ", TenantConstant.DbaTenantName));
                        //context.AddOrUpdates(appModules);
                        //context.Database.ExecuteSqlCommand(string.Format("SET IDENTITY_INSERT [{0}].[tenant_TenantUserAppModule] OFF ", TenantConstant.DbaTenantName));

                        //DbLoginUserUtil.CreateTenantDbLoginUser(tenantDba, connString);//创建数据库登录用户
                        //DbLoginUserUtil.CreateTenantDbLoginUser(tenantDev, connString);//创建数据库登录用户
                        //DbLoginUserUtil.CreateTenantDbLoginUser(tenantBuy, connString);//创建数据库登录用户
                        //DbLoginUserUtil.CreateTenantDbLoginUser(tenantSale, connString);//创建数据库登录用户
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        LogUtil.LogFatal(string.Format("-------Admin Config insert Tenant Pool is failed. \r\nMessage: {0}. \r\nStackTrace: {1}", ex.Message, ex.StackTrace));
                    }
                }
                #endregion
            }

        }
    }
}
